import axios from "axios"
import type { AxiosInstance, AxiosError } from "axios";

/**
 * 创建 Flowable API 客户端
 */
export function createFlowableClient(
  baseURL: string,
  username: string,
  password: string
): AxiosInstance {
  const token = btoa(`${username}:${password}`);

  const instance = axios.create({
    baseURL,
    headers: {
      Authorization: `Basic ${token}`,
    },
    timeout: 10000, // 超时时间10秒，可根据情况调整
  });

  /** ------------------- 请求拦截器 ------------------- */
  instance.interceptors.request.use(
    (config) => {
      console.log(
        `[Flowable Request] → ${config.method?.toUpperCase()} ${config.url}`
      );
      return config;
    },
    (error) => {
      console.error("[Flowable Request Error]", error);
      return Promise.reject(error);
    }
  );

  /** ------------------- 响应拦截器 ------------------- */
  instance.interceptors.response.use(
    (response) => {
      console.log(
        `[Flowable Response] ← ${response.config.url} (${response.status})`
      );
      return response;
    },
    (error: AxiosError) => {
      if (error.response) {
        const { status, config } = error.response;
        console.error(`[Flowable Error] ${status} ${config.url}`);

        switch (status) {
          case 401:
            console.warn("⚠️  未授权或登录已过期，请检查用户名/密码。");
            break;
          case 404:
            console.warn("⚠️  请求的资源不存在。");
            break;
          case 500:
            console.warn("⚠️  服务器内部错误，请稍后重试。");
            break;
          default:
            console.warn(`⚠️  未知错误: ${status}`);
        }
      } else {
        console.error("[Flowable Network Error]", error.message);
      }
      return Promise.reject(error);
    }
  );

  return instance;
}
